package com.lrkj.seetaface.service.impl;

import com.cnsugar.ai.face.FaceHelper;
import com.lrkj.facefeature.mapper.FaceFeatureMapper;
import com.lrkj.seetaface.service.SeetFaceService;
import com.lrkj.util.Base64ToFile;
import com.lrkj.util.Float2Byte;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * 人脸识别seet service 业务层处理
 *
 * @author wyd
 * @date 2022-07-13
 */
@Service
public class SeetFaceServiceImpl implements SeetFaceService {

    @Autowired
    private FaceFeatureMapper faceFeatureMapper;

    @Override
    public String faceDisplayImg(String base64img) throws IOException {
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        if(base64img==null||"".equals(base64img)){
            return "上传失败，上传图片数据为空";
        }else {
            String [] d = base64img.split("base64,");//将字符串分成数组
            if(d != null && d.length == 2){
                dataPrix = d[0];
                data = d[1];
            }else {
                return "上传失败，数据不合法";
            }
        }
        //图片存本地
        String time=String.valueOf(System.currentTimeMillis());
        Base64ToFile.base64ToFile("F:\\01wyd\\02facedis\\img",data,time+".png");
        String path="F:\\01wyd\\02facedis\\img\\"+time+".png";
        //比对
        String img1 = path;
        String img2 = "F:\\01wyd\\02facedis\\img\\base.png";
//        float[] features1 = FaceHelper.extractMaxFace(ImageIO.read(new File(img1)));
//        float[] features2 = FaceHelper.extractMaxFace(ImageIO.read(new File(img2)));

        byte[] face1 = FaceHelper.cropFace(ImageIO.read(new File(img1)))[0];
        byte[] face2 = FaceHelper.cropFace(ImageIO.read(new File(img2)))[0];
        float[] features1 = FaceHelper.extractCroppedFace(face1);
        float[] features2 = FaceHelper.extractCroppedFace(face2);

        System.out.println("features1: "+ Arrays.toString(features1));
        System.out.println("features2: "+Arrays.toString(features2));
        System.out.println("seeta相似度:" + FaceHelper.calculateSimilarity(features1, features2));

        //信息存数据库
        com.lrkj.facefeature.domain.FaceFeature  feature=new com.lrkj.facefeature.domain.FaceFeature();
        feature.setFace_feature_data(Float2Byte.asByteArray(features1));
        feature.setFace_img_path(path);
        feature.setEngine_type("2");
        faceFeatureMapper.insertFaceFeature(feature);
        return "相似度："+FaceHelper.calculateSimilarity(features1, features2);
    }
}
